package com.jp.knowledge.activity;

import android.view.View;

import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.model.NetLogModel;
import com.jp.knowledge.util.NetLogUtil;
import com.jp.knowledge.webUtil.X5WebView;

import java.util.List;

import rx.Observer;

/**
 * Created by 528787067@qq.com on 2017/2/15.
 */

public class NetLogActivity extends SlidingActivity implements View.OnClickListener {

    private X5WebView logView;

    private Observer<List<NetLogModel>> getLogObserver = new Observer<List<NetLogModel>>() {
        @Override
        public void onCompleted() {}
        @Override
        public void onError(Throwable e) {}
        @Override
        public void onNext(List<NetLogModel> netLogModels) {
            if(logView == null)
                return;
            String logStr = "<body>";
            for(int i = netLogModels.size()-1; i >= 0; i--){
                NetLogModel data = netLogModels.get(i);
                logStr += ("<br/>"
                        + "<nobr>　访问类型：" + data.getType() + "　</nobr><br/>"
                        + "<nobr>　请求时间：" + data.getRequestTime() + "　</nobr><br/>"
                        + "<nobr>　响应时间：" + data.getResponseTime() + "　</nobr><br/>"
                        + "<nobr>　访问连接：" + data.getUrl() + "　</nobr><br/>"
                        + "<nobr>　请求参数：" + data.getRequestParam() + "　</nobr><br/>"
                        + "<nobr>　错误代码：" + data.getErrorCode() + "　</nobr><br/>"
                        + "<nobr>　错误信息：" + data.getMessage() + "　</nobr><br/>"
                        + "<br/>");
            }
            logStr += "</body>";
            logView.loadData(logStr, "text/html; charset=utf-8", null);
        }
    };

    @Override
    protected int getResourceId() {
        return R.layout.activity_net_log;
    }

    @Override
    protected void init() {
        logView = (X5WebView) this.findViewById(R.id.showLogView);

        rightBtn.setText("清空");
        topName.setText("网络请求日志");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setVisibility(View.VISIBLE);
        rightBtn.setVisibility(View.VISIBLE);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(this);
        rightBtn.setOnClickListener(this);

        NetLogUtil.getNetMsgFromLocal(getLogObserver);
    }

    @Override
    protected void onDestroy() {
        logView.destroy();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.right_bn:
                NetLogUtil.clearNetLog();
                logView.clearView();
                logView.loadData("", "text/html; charset=utf-8", null);
                break;
        }
    }
}
